Custom drawing
LiveCharts draws every chart with SkiaSharp, and you can add your own shapes to that drawing. There are three ways: visual elements add shapes, labels or layouts to the chart and the chart places and animates them for you; visual states change how a single point is drawn, for example its fill, while the app runs; and you can also add geometries straight to the canvas of the chart. Visual elements are the recommended way to draw a custom element in a chart.
This article highlights the most used features. Every member is listed in the API explorer:
Visual,
DrawnLabelVisual,
VisualStatesDictionary and
CoreMotionCanvas.
In XAML, declare a label visual as XamlDrawnLabelVisual, and the states of a series with ChartPointState and Set.
Visual elements
The VisualElements property of a chart takes a collection of IChartElement. Inherit from the Visual class to
define an element: the chart adds it to the canvas, animates it, and removes it when it leaves the collection. This
sample adds ten visuals to a chart, each one is a class in the code below and is explained in the next sections.

<UserControl
x:Class="WPFSample.General.VisualElements.View"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:lvc="clr-namespace:LiveChartsCore.SkiaSharpView.WPF;assembly=LiveChartsCore.SkiaSharpView.WPF"
xmlns:vms="clr-namespace:ViewModelsSamples.General.VisualElements;assembly=ViewModelsSamples">
<UserControl.DataContext>
<vms:ViewModel/>
</UserControl.DataContext>
<lvc:CartesianChart
VisualElements="{Binding VisualElements}">
</lvc:CartesianChart>
</UserControl>
using System.Collections.Generic;
using LiveChartsCore.Kernel;
namespace ViewModelsSamples.General.VisualElements;
public class ViewModel
{
public IEnumerable<IChartElement> VisualElements { get; set; } = [
new RectangleVisual(),
new ScaledRectangleVisual(),
new PointerDownAwareVisual(),
new SvgVisual(),
new ThemedVisual(),
new CustomVisual(),
new AbsoluteVisual(),
new StackedVisual(),
new TableVisual(),
new ContainerVisual(),
];
}
using LiveChartsCore;
using LiveChartsCore.Drawing;
using LiveChartsCore.SkiaSharpView.Drawing.Geometries;
using LiveChartsCore.SkiaSharpView.Drawing.Layouts;
using LiveChartsCore.SkiaSharpView.Painting;
using LiveChartsCore.VisualElements;
using SkiaSharp;
namespace ViewModelsSamples.General.VisualElements;
public class AbsoluteVisual : Visual
{
protected override AbsoluteLayout DrawnElement { get; } =
new AbsoluteLayout
{
// X and Y coordinates are relative to the parent
Children = [
new RectangleGeometry
{
X = 0,
Y = 0,
Width = 40,
Height = 40,
Fill = new SolidColorPaint(SKColors.Gray)
},
new LabelGeometry
{
X = 10,
Y = 10,
Text = "Hello",
TextSize = 10,
HorizontalAlign = Align.Start,
VerticalAlign = Align.Start,
Paint = new SolidColorPaint(SKColors.Black)
}
]
};
protected override void Measure(Chart chart)
{
DrawnElement.X = 300;
DrawnElement.Y = 100;
DrawnElement.Width = 40;
DrawnElement.Height = 40;
}
}
using LiveChartsCore;
using LiveChartsCore.Drawing;
using LiveChartsCore.SkiaSharpView.Drawing.Geometries;
using LiveChartsCore.SkiaSharpView.Drawing.Layouts;
using LiveChartsCore.SkiaSharpView.Painting;
using LiveChartsCore.VisualElements;
using SkiaSharp;
namespace ViewModelsSamples.General.VisualElements;
public class ContainerVisual : Visual
{
private readonly Container _container;
public ContainerVisual()
{
_container = new Container
{
Content = new LabelGeometry
{
Text = "Hello",
TextSize = 20,
Padding = new(10),
Paint = new SolidColorPaint(SKColors.Black),
VerticalAlign = Align.Start,
HorizontalAlign = Align.Start
}
};
_container.Geometry.Stroke = new SolidColorPaint(SKColors.Black, 3);
_container.Geometry.Fill = new SolidColorPaint(SKColors.LightGray);
}
protected override Container DrawnElement => _container;
protected override void Measure(Chart chart)
{
DrawnElement.X = 500;
DrawnElement.Y = 100;
}
}
using LiveChartsCore.Drawing;
using LiveChartsCore.SkiaSharpView.Drawing;
namespace ViewModelsSamples.General.VisualElements;
public class CustomSkiaShape : BoundedDrawnGeometry, IDrawnElement<SkiaSharpDrawingContext>
{
public void Draw(SkiaSharpDrawingContext context)
{
var canvas = context.Canvas;
var paint = context.ActiveSkiaPaint;
var x = X + Width / 2f;
var y = Y + Height / 2f;
var r = (float)Width / 2f;
canvas.DrawCircle(x, y, r, paint);
canvas.DrawCircle(x, y, r * 0.75f, paint);
canvas.DrawCircle(x, y, r * 0.5f, paint);
}
}
using LiveChartsCore;
using LiveChartsCore.SkiaSharpView.Painting;
using LiveChartsCore.VisualElements;
using SkiaSharp;
namespace ViewModelsSamples.General.VisualElements;
public class CustomVisual : Visual
{
protected override CustomSkiaShape DrawnElement { get; } =
new CustomSkiaShape { Stroke = new SolidColorPaint(SKColors.Red) };
protected override void Measure(Chart chart)
{
DrawnElement.X = 250;
DrawnElement.Y = 100;
DrawnElement.Width = 40;
DrawnElement.Height = 40;
}
}
using System.Diagnostics;
using LiveChartsCore;
using LiveChartsCore.Kernel.Events;
using LiveChartsCore.SkiaSharpView.Drawing.Geometries;
using LiveChartsCore.SkiaSharpView.Painting;
using LiveChartsCore.VisualElements;
using SkiaSharp;
namespace ViewModelsSamples.General.VisualElements;
public class PointerDownAwareVisual : Visual
{
public PointerDownAwareVisual()
{
PointerDown += OnPointerDown;
}
private void OnPointerDown(IInteractable visual, VisualElementEventArgs visualElementsArgs)
{
var location = visualElementsArgs.PointerLocation;
Trace.WriteLine($"Pointer down at {location.X}, {location.Y}");
}
protected override RectangleGeometry DrawnElement { get; } =
new RectangleGeometry { Fill = new SolidColorPaint(SKColors.Red) };
protected override void Measure(Chart chart)
{
DrawnElement.X = 150;
DrawnElement.Y = 100;
DrawnElement.Width = 40;
DrawnElement.Height = 40;
}
}
using LiveChartsCore;
using LiveChartsCore.SkiaSharpView.Drawing.Geometries;
using LiveChartsCore.SkiaSharpView.Painting;
using LiveChartsCore.VisualElements;
using SkiaSharp;
namespace ViewModelsSamples.General.VisualElements;
public class RectangleVisual : Visual
{
protected override RectangleGeometry DrawnElement { get; } =
new RectangleGeometry { Fill = new SolidColorPaint(SKColors.Red) };
protected override void Measure(Chart chart)
{
DrawnElement.X = 100;
DrawnElement.Y = 100;
DrawnElement.Width = 40;
DrawnElement.Height = 40;
}
}
using LiveChartsCore;
using LiveChartsCore.Drawing;
using LiveChartsCore.Kernel.Sketches;
using LiveChartsCore.SkiaSharpView.Drawing.Geometries;
using LiveChartsCore.SkiaSharpView.Painting;
using LiveChartsCore.VisualElements;
using SkiaSharp;
namespace ViewModelsSamples.General.VisualElements;
public class ScaledRectangleVisual : Visual
{
protected override RectangleGeometry DrawnElement { get; } =
new RectangleGeometry { Fill = new SolidColorPaint(SKColors.Red) };
protected override void Measure(Chart chart)
{
var cartesianChart = (ICartesianChartView)chart.View;
// use the ScaleDataToPixels function to scale data.
var locationInDataScale = new LvcPointD(5, 5);
var locationInPixels = cartesianChart.ScaleDataToPixels(locationInDataScale);
DrawnElement.X = (float)locationInPixels.X;
DrawnElement.Y = (float)locationInPixels.Y;
DrawnElement.Width = 40;
DrawnElement.Height = 40;
}
}
using LiveChartsCore;
using LiveChartsCore.Drawing;
using LiveChartsCore.SkiaSharpView.Drawing.Geometries;
using LiveChartsCore.SkiaSharpView.Drawing.Layouts;
using LiveChartsCore.SkiaSharpView.Painting;
using LiveChartsCore.VisualElements;
using SkiaSharp;
namespace ViewModelsSamples.General.VisualElements;
public class StackedVisual : Visual
{
protected override StackLayout DrawnElement { get; } =
new StackLayout
{
// X and Y coordinates are relative to the parent
Orientation = ContainerOrientation.Vertical,
Children = [
new CircleGeometry
{
Width = 40,
Height = 40,
Fill = new SolidColorPaint(SKColors.CadetBlue)
},
new RectangleGeometry
{
Width = 40,
Height = 40,
Fill = new SolidColorPaint(SKColors.DeepSkyBlue)
},
new DiamondGeometry
{
Width = 40,
Height = 40,
Fill = new SolidColorPaint(SKColors.LightSteelBlue)
}
]
};
protected override void Measure(Chart chart)
{
DrawnElement.X = 350;
DrawnElement.Y = 100;
}
}
using LiveChartsCore;
using LiveChartsCore.Drawing;
using LiveChartsCore.SkiaSharpView.Drawing.Geometries;
using LiveChartsCore.SkiaSharpView.Painting;
using LiveChartsCore.VisualElements;
using SkiaSharp;
namespace ViewModelsSamples.General.VisualElements;
public class SvgVisual : Visual
{
protected override VariableSVGPathGeometry DrawnElement { get; } =
new VariableSVGPathGeometry
{
Stroke = new SolidColorPaint(SKColors.Blue),
Path = SKPath.ParseSvgPathData(SVGPoints.Star)
};
protected override void Measure(Chart chart)
{
DrawnElement.X = 200;
DrawnElement.Y = 100;
DrawnElement.Width = 40;
DrawnElement.Height = 40;
}
}
using LiveChartsCore;
using LiveChartsCore.Drawing;
using LiveChartsCore.SkiaSharpView.Drawing.Geometries;
using LiveChartsCore.SkiaSharpView.Drawing.Layouts;
using LiveChartsCore.SkiaSharpView.Painting;
using LiveChartsCore.VisualElements;
using SkiaSharp;
namespace ViewModelsSamples.General.VisualElements;
public class TableVisual : Visual
{
protected override TableLayout DrawnElement { get; } =
new TableLayout
{
Cells = [
new(0, 0, GetLabel("A")),
new(0, 1, GetLabel("-")),
new(0, 2, GetLabel("B")),
new(1, 0, GetLabel("-")),
new(1, 1, GetLabel("C")),
new(1, 2, GetLabel("-"))
],
};
protected override void Measure(Chart chart)
{
DrawnElement.X = 400;
DrawnElement.Y = 100;
}
private static LabelGeometry GetLabel(string text) =>
new()
{
Text = text,
TextSize = 20,
Padding = new(10),
Paint = new SolidColorPaint(SKColors.Black),
VerticalAlign = Align.Start,
HorizontalAlign = Align.Start
};
}
using LiveChartsCore;
using LiveChartsCore.SkiaSharpView.Drawing.Geometries;
using LiveChartsCore.SkiaSharpView.Painting;
using LiveChartsCore.Themes;
using LiveChartsCore.VisualElements;
using SkiaSharp;
namespace ViewModelsSamples.General.VisualElements;
public class ThemedVisual : Visual
{
private object _themeId = new();
private static bool _isThemeRegistered;
protected override RectangleGeometry DrawnElement { get; } =
new RectangleGeometry();
protected override void Measure(Chart chart)
{
if (!_isThemeRegistered) RegisterTheme();
ApplyTheme(chart.GetTheme());
DrawnElement.X = 600;
DrawnElement.Y = 100;
DrawnElement.Width = 40;
DrawnElement.Height = 40;
}
private void ApplyTheme(Theme theme)
{
if (theme.ThemeId == _themeId) return;
theme.ApplyStyleTo<ThemedVisual>(this);
_themeId = theme.ThemeId;
}
private void RegisterTheme()
{
// now lets define the default style for the visual
// ideally you should do this in the application startup
var theme = LiveCharts.DefaultSettings.GetTheme();
theme.HasRuleFor<ThemedVisual>(visual =>
{
visual.DrawnElement.Fill =
theme.IsDark
? new SolidColorPaint(SKColors.White)
: new SolidColorPaint(SKColors.Black);
});
_isThemeRegistered = true;
}
}
Place a visual
A Visual overrides two members. DrawnElement is the shape it draws; the property is declared as IDrawnElement,
and the override can return a more specific type, such as RectangleGeometry, thanks to
covariant returns.
Measure runs every time the chart updates, and sets the position and size of the shape, in pixels from the top-left
corner of the chart:
public class RectangleVisual : Visual
{
protected override RectangleGeometry DrawnElement { get; } =
new RectangleGeometry { Fill = new SolidColorPaint(SKColors.Red) };
protected override void Measure(Chart chart)
{
DrawnElement.X = 100; // mark
DrawnElement.Y = 100; // mark
DrawnElement.Width = 40;
DrawnElement.Height = 40;
}
}
To place the shape at a data coordinate, convert it with ScaleDataToPixels (the ScaledRectangleVisual class in the
sample):
protected override void Measure(Chart chart)
{
var cartesianChart = (ICartesianChartView)chart.View;
var locationInPixels = cartesianChart.ScaleDataToPixels(new LvcPointD(5, 5)); // mark
DrawnElement.X = (float)locationInPixels.X;
DrawnElement.Y = (float)locationInPixels.Y;
DrawnElement.Width = 40;
DrawnElement.Height = 40;
}
When a property of the drawn element changes, it animates to the new value with the animation of the chart. Set the
Easing and AnimationSpeed of the visual to use a different animation for it. IsVisible shows or hides the visual.
Labels
DrawnLabelVisual draws a text. Pass it a LabelGeometry with the text, the size and the position; when its paint is
not set, the theme picks it. It is the same visual the Title of a chart uses.
VisualElements = new IChartElement[]
{
new DrawnLabelVisual(
new LabelGeometry
{
Text = "Hello",
TextSize = 20,
X = 100,
Y = 50
})
};
Geometries and SVG paths
DrawnElement can be any geometry of the LiveChartsCore.SkiaSharpView.Drawing.Geometries namespace, such as
RectangleGeometry, CircleGeometry, DiamondGeometry or LabelGeometry. To draw an SVG path, use a
VariableSVGPathGeometry and set its Path (the SvgVisual class in the sample):
protected override VariableSVGPathGeometry DrawnElement { get; } =
new VariableSVGPathGeometry
{
Stroke = new SolidColorPaint(SKColors.Blue),
Path = SKPath.ParseSvgPathData(SVGPoints.Star) // mark
};
Custom geometries
To draw anything else, write your own geometry with the SkiaSharp API. Inherit from BoundedDrawnGeometry, which
already has animated X, Y, Width and Height properties, and implement IDrawnElement<SkiaSharpDrawingContext>.
Draw runs once for each paint of the geometry, its Fill and then its Stroke; context.Canvas is the SkiaSharp
canvas and context.ActiveSkiaPaint the paint being drawn:

public class CustomSkiaShape : BoundedDrawnGeometry, IDrawnElement<SkiaSharpDrawingContext>
{
public void Draw(SkiaSharpDrawingContext context)
{
var canvas = context.Canvas; // mark
var paint = context.ActiveSkiaPaint; // mark
var x = X + Width / 2f;
var y = Y + Height / 2f;
var r = (float)Width / 2f;
canvas.DrawCircle(x, y, r, paint);
canvas.DrawCircle(x, y, r * 0.75f, paint);
canvas.DrawCircle(x, y, r * 0.5f, paint);
}
}
The CustomVisual class in the sample returns this geometry as its DrawnElement. To add your own animated
properties to a geometry, see draw on the canvas.
Layouts
A layout is a drawn element that positions other elements; the library uses them to build the tooltips and the
legends. They are in the LiveChartsCore.SkiaSharpView.Drawing.Layouts namespace:
AbsoluteLayoutplaces itsChildrenat their ownXandY, relative to the position of the layout (AbsoluteVisualin the sample).StackLayoutplaces itsChildrenone after the other, setOrientationto stack them vertically or horizontally (StackedVisual).TableLayoutplaces itsCellsin rows and columns, each cell takes the row, the column and the element (TableVisual).Containerdraws a shape behind itsContentand takes the size of the content; set theFillandStrokeof itsGeometryto paint the background and the border (ContainerVisual).

protected override TableLayout DrawnElement { get; } =
new TableLayout
{
Cells = [
new(0, 0, GetLabel("A")),
new(0, 1, GetLabel("-")),
new(0, 2, GetLabel("B")),
new(1, 0, GetLabel("-")),
new(1, 1, GetLabel("C")),
new(1, 2, GetLabel("-"))
],
};
Themes
A visual can take its paints from the theme, so it changes with the light and dark modes. The ThemedVisual class in
the sample registers a rule for its type with HasRuleFor<ThemedVisual>, and applies it with
theme.ApplyStyleTo<ThemedVisual>(this) when the theme of the chart changes: the fill is white on a dark theme and
black on a light one. See the themes article
for more about rules.
Pointer events
A Visual raises PointerDown when the pointer goes down over it (the PointerDownAwareVisual class in the sample).
The element is hit when the pointer is inside the rectangle that starts at the X and Y of the drawn element and has
its measured size.
public PointerDownAwareVisual()
{
PointerDown += OnPointerDown; // mark
}
private void OnPointerDown(IInteractable visual, VisualElementEventArgs args)
{
var location = args.PointerLocation;
Trace.WriteLine($"Pointer down at {location.X}, {location.Y}");
}
The chart also raises VisualElementsPointerDown (VisualElementsPointerDownCommand in XAML) with
every visual under the pointer, see the events article.
Drawing order
By default a visual is drawn on top of the series, which is what you normally want for glyphs, callouts or markers.
To draw it behind the series, for example as a background, set its ZIndex to a negative value. It is then drawn
before everything else on the canvas, so a filled draw margin frame covers it.
new RectangleVisual { ZIndex = -1 };
A ZIndex of 0 (the default) or a positive value keeps the visual on top of the series. Visuals on the same side of
the series are drawn in ZIndex order, so a visual with a higher ZIndex covers one with a lower value. The ZIndex
can change at run time, and the visual moves to the other side of the series when its sign changes.
Per point states
A visual state is a named set of property values for the shape of a point. Define the states of a series with
HasState (or in XAML, with ChartPointState items in its AdditionalVisualStates), then apply one
to a point with SetState and remove it with ClearState. Removing a state restores the values the shape had before.
The PointMeasured event (a command in the XAML samples) runs every time a point is measured, so it can choose the
states from the data. In this sample the columns and their labels turn red when the value is greater than 5.

<UserControl
x:Class="WPFSample.General.ConditionalDraw.View"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:lvc="clr-namespace:LiveChartsCore.SkiaSharpView.WPF;assembly=LiveChartsCore.SkiaSharpView.WPF"
xmlns:vms="clr-namespace:ViewModelsSamples.General.ConditionalDraw;assembly=ViewModelsSamples">
<UserControl.DataContext>
<vms:ViewModel/>
</UserControl.DataContext>
<lvc:CartesianChart TooltipPosition="Bottom">
<lvc:CartesianChart.Series>
<lvc:SeriesCollection>
<lvc:XamlColumnSeries
ShowDataLabels="True"
DataLabelsSize="15"
Values="{Binding Values}"
PointMeasuredCommand="{Binding PointMeasuredCommand}">
<!--
Use the AdditionalVisualStates property to define the look of the points
when they are in a different state
-->
<lvc:XamlColumnSeries.AdditionalVisualStates>
<!-- When the state is "Danger", the Fill is set to red -->
<lvc:ChartPointState Name="Danger">
<lvc:ChartPointState.Setters>
<lvc:Set
PropertyName="Fill"
Value="{lvc:SolidColorPaint Color='#f00'}"/>
</lvc:ChartPointState.Setters>
</lvc:ChartPointState>
<lvc:ChartPointState Name="LabelDanger">
<lvc:ChartPointState.Setters>
<lvc:Set
PropertyName="Paint"
Value="{lvc:SolidColorPaint Color='#f00'}"/>
<lvc:Set
PropertyName="TextSize"
Value="30"/>
</lvc:ChartPointState.Setters>
</lvc:ChartPointState>
<!-- The "Hover" state is fired when the pointer is over a point-->
<lvc:ChartPointState Name="Hover">
<lvc:ChartPointState.Setters>
<lvc:Set
PropertyName="DropShadow"
Value="{lvc:Shadow '4, 16, #00f'}"/>
</lvc:ChartPointState.Setters>
</lvc:ChartPointState>
</lvc:XamlColumnSeries.AdditionalVisualStates>
</lvc:XamlColumnSeries>
</lvc:SeriesCollection>
</lvc:CartesianChart.Series>
</lvc:CartesianChart>
</UserControl>
using System;
using System.Collections.ObjectModel;
using LiveChartsCore.Defaults;
using CommunityToolkit.Mvvm.Input;
using LiveChartsCore.Kernel;
using System.Threading.Tasks;
namespace ViewModelsSamples.General.ConditionalDraw;
public partial class ViewModel
{
public ViewModel()
{
Randomize();
}
public ObservableCollection<ObservableValue> Values { get; set; } =
[
new(2),
new(3),
new(4)
];
[RelayCommand]
private void OnPointMeasured(ChartPoint point)
{
var ctx = point.Context;
if (ctx.DataSource is not ObservableValue observable) return;
var states = ctx.Series.VisualStates;
if (observable.Value > 5)
{
states.SetState("Danger", ctx.Visual);
states.SetState("LabelDanger", ctx.Label);
}
else
{
states.ClearState("Danger", ctx.Visual);
states.ClearState("LabelDanger", ctx.Label);
}
}
private async void Randomize()
{
var r = new Random();
while (true)
{
await Task.Delay(3000);
foreach (var item in Values)
{
item.Value = r.Next(0, 10);
}
}
}
}
The properties a state sets belong to the drawn shape, point.Context.Visual, or to its data label,
point.Context.Label; a Fill set by a state replaces the paint of the series for that shape only:
columnSeries.HasState("Danger", [
(nameof(IDrawnElement.Fill), new SolidColorPaint(SKColors.Red)) // mark
]);
columnSeries.PointMeasured += point =>
{
var ctx = point.Context;
if (ctx.DataSource is not ObservableValue observable) return;
if (observable.Value > 5)
ctx.Series.VisualStates.SetState("Danger", ctx.Visual); // mark
else
ctx.Series.VisualStates.ClearState("Danger", ctx.Visual); // mark
};
The library applies the Hover state when the pointer enters a point and clears it when the pointer leaves. The
default theme defines it for every series: it lowers the opacity of the shape, except on line, step line and polar line
series, where it scales the point up instead. A Hover state you define replaces the one of the theme, as the sample
does to draw a shadow.
To change a point only once, when it is measured, without restoring it later, see customize each point.
Draw on the canvas
You can also add a geometry straight to the canvas of the chart. This is what a Visual does for you, so it is
normally the easier option, but drawing on the canvas shows how geometries and animations work in the library.
The sample adds a circle at the data coordinate (5, 5), and animates its size when the chart is clicked.

<UserControl
x:Class="WPFSample.General.DrawOnCanvas.View"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:lvc="clr-namespace:LiveChartsCore.SkiaSharpView.WPF;assembly=LiveChartsCore.SkiaSharpView.WPF"
xmlns:vms="clr-namespace:ViewModelsSamples.General.DrawOnCanvas;assembly=ViewModelsSamples">
<UserControl.DataContext>
<vms:ViewModel/>
</UserControl.DataContext>
<lvc:CartesianChart
UpdateStartedCommand="{Binding ChartUpdatedCommand}"
PointerPressedCommand="{Binding ChartPressedCommand}"/>
</UserControl>
using System;
using CommunityToolkit.Mvvm.Input;
using LiveChartsCore;
using LiveChartsCore.Drawing;
using LiveChartsCore.Generators;
using LiveChartsCore.Kernel;
using LiveChartsCore.Kernel.Events;
using LiveChartsCore.Kernel.Sketches;
using LiveChartsCore.SkiaSharpView.Drawing;
using LiveChartsCore.SkiaSharpView.Painting;
using SkiaSharp;
namespace ViewModelsSamples.General.DrawOnCanvas;
// in this example, we use the UpdateStartedCommand to add our custom // mark
// geometry to the chart, then we use the PointerPressedCommand to change the //mark
// size of the geometry when the user clicks on it. // mark
public partial class ViewModel
{
private bool _isBig;
private readonly MotionGeometry _geometry = new()
{
Diameter = 20,
Fill = new SolidColorPaint(SKColors.Blue.WithAlpha(100)),
Stroke = new SolidColorPaint(SKColors.Blue, strokeWidth: 3)
};
[RelayCommand]
public void ChartUpdated(ChartCommandArgs args)
{
var chartView = (ICartesianChartView)args.Chart;
// lets place the geometry at (5, 5) in the chart values scale
var locationInChartValues = new LvcPointD(5, 5);
var locationInPixels = chartView.ScaleDataToPixels(locationInChartValues);
_geometry.X = (float)locationInPixels.X;
_geometry.Y = (float)locationInPixels.Y;
_geometry.Initialize(args);
}
[RelayCommand]
public void ChartPressed(PointerCommandArgs args)
{
_geometry.Diameter = _isBig ? 20 : 70;
_isBig = !_isBig;
args.Chart.Invalidate();
}
}
public partial class MotionGeometry : BoundedDrawnGeometry, IDrawnElement<SkiaSharpDrawingContext>
{
private bool _isInitialized;
// The MotionProperty attribute makes the property animatable, // mark
// both the property and the class must be marked as partial // mark
// partial properties were introduced in C# 13 // mark
// A motion property will animate any change in the property // mark
// according to the Animation defined in the Animate method. // mark
[MotionProperty]
public partial float Diameter { get; set; }
public void Draw(SkiaSharpDrawingContext context)
{
// we can use SkiaSharp here to draw anything we need // mark
// https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/graphics/skiasharp/basics/ // mark
// because we inherited from BoundedDrawnGeometry, this class already contains the X, Y
// and some other motion properties that we can use.
var paint = context.ActiveSkiaPaint;
context.Canvas.DrawCircle(X, Y, Diameter, paint);
}
public void Initialize(ChartCommandArgs args)
{
if (_isInitialized) return;
args.Chart.CoreChart.Canvas.AddGeometry(this);
var animation = new Animation(
easingFunction: EasingFunctions.BounceOut,
duration: TimeSpan.FromMilliseconds(800));
this.Animate(animation);
_isInitialized = true;
}
}
The UpdateStarted event (UpdateStartedCommand in XAML) runs every time the chart updates, after
the axes, the series and the visual elements were measured and before the chart is drawn, so ScaleDataToPixels returns
the current position there. The sample adds the geometry once with chart.CoreChart.Canvas.AddGeometry(...); a geometry
added to the canvas is drawn with its own Fill and Stroke, on top of the series.
The Diameter of MotionGeometry is a motion property: every time it changes, it animates from the current value to the
new one, using the animation set with Animate. The [MotionProperty] attribute generates that code, it needs the
LiveChartsGenerators package, and both the class and the property must be partial (partial properties need
C# 13 or later):
<PackageReference Include="LiveChartsGenerators" Version="1.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>analyzers</IncludeAssets>
</PackageReference>
The drawing happens in these steps:
- The chart updates when its data, its size or one of its properties changes. It measures its elements and raises
UpdateStarted. - Adding paints and geometries to the canvas only schedules them, nothing is drawn yet.
- The canvas draws every paint and geometry, this is when
Drawruns. - While any animation is running, the canvas draws a new frame again and again until every animation has finished,
so
Drawruns many times per second. Only draw inDraw; set the values in the update.